package com.mashibing.constraints;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateTimeCheckValidator implements ConstraintValidator<DataTimeCheck, Object> {

    private DataTimeCheck dataTimeCheck;

    @Override
    public void initialize(DataTimeCheck constraintAnnotation) {
        dataTimeCheck = constraintAnnotation;
        ConstraintValidator.super.initialize(constraintAnnotation);
    }

    @Override
    public boolean isValid(Object dataTime, ConstraintValidatorContext constraintValidatorContext) {
        LocalDateTime time = null;
        String judge = dataTimeCheck.judge();

        if (dataTime == null) {
            return true;
        }

        if (dataTime instanceof LocalDateTime) {
            time = (LocalDateTime) dataTime;
        }

        if (dataTime instanceof String) {
            time = LocalDateTime.parse((String) dataTime, DateTimeFormatter.ofPattern(dataTimeCheck.pattern()));
        }

        if (judge.equals(DataTimeCheck.IS_AFTER)) {
            assert time != null;
            if (time.isAfter(LocalDateTime.now())) {
                return true;
            }
        }

        if (judge.equals(DataTimeCheck.IS_BEFORE)) {
            assert time != null;
            return time.isBefore(LocalDateTime.now());
        }
        return false;
    }
}
